package cn.xkai.exercise.a;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @description: 字符串中的第一个唯一字符
 * 给定一个字符串 s ，找到 它的第一个不重复的字符，并返回它的索引 。如果不存在，则返回 -1 。
 * 1 <= s.length <= 105
 * s 只包含小写字母
 * <p>
 * 自己的思路：暴力遍历、LinkedHashMap
 * 借鉴的思路：手写hash
 * @author: kaixiang
 * @date: 2022/7/5
 **/
public class Solution32 {
    public int firstUniqChar(String s) {
        for (int i = 0; i < s.length(); i++) {
            boolean flag = true;
            for (int j = 0; j < s.length(); j++) {
                if (i != j && s.charAt(i) == s.charAt(j)) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                return i;
            }
        }
        return -1;
    }

    public int firstUniqCharHashmap(String s) {
        LinkedHashMap<Character, Integer> map = new LinkedHashMap<>();
        for (int i = 0; i < s.length(); i++) {
            if (map.containsKey(s.charAt(i))) {
                map.put(s.charAt(i), -1);
                continue;
            }
            map.put(s.charAt(i), i);
        }
        for (Map.Entry<Character, Integer> entry : map.entrySet()) {
            if (entry.getValue() != -1) {
                return entry.getValue();
            }
        }
        return -1;
    }

    public int firstUniqCharHash(String s) {
        int[] a = new int[26];
        int[] index = new int[26];
        int len = s.length();
        for (int i = 0; i < len; i++) {
            a[s.charAt(i) - 'a']++;
            index[s.charAt(i) - 'a'] = i;
        }
        for (int i = 0; i < len; i++) {
            if (a[s.charAt(i) - 'a'] == 1) {
                return index[s.charAt(i) - 'a'];
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        String s = "loveleetcode";
        Solution32 solution32 = new Solution32();
        System.out.println(solution32.firstUniqChar(s));
        System.out.println(solution32.firstUniqCharHashmap(s));
        System.out.println(solution32.firstUniqCharHash(s));
    }
}
